package org.sack.scratchpad;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.Writer;
import java.util.Properties;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.Utilities;
import org.sack.scratchpad.txt_file_filter;

/**
 * Top component which displays something.
 */
final class scratch_padTopComponent extends TopComponent {

    private static scratch_padTopComponent instance;
    //instance.grabFocus();
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "org/sack/sackscratchpad/icon.gif";
    static Properties prop = new Properties();
    static final String PREFERRED_ID = "scratch_padTopComponent";
    static int count=0,current=0,start=0;
        
    // count stores highest no of scrap stored
    // start stores lowest no of scrap stored
    // current stores currently displayed scrap 
    

    



    private scratch_padTopComponent() {
 
            count=0;
            current=0;
            start=1;
            

            initComponents();
            setName(NbBundle.getMessage(scratch_padTopComponent.class, "CTL_scratch_padTopComponent"));
            setToolTipText(NbBundle.getMessage(scratch_padTopComponent.class, "HINT_scratch_padTopComponent"));
            setIcon(Utilities.loadImage(ICON_PATH, true));
                      

    }

    static void display(int n){
        try {
            
            String[] str = new String[10];
            String str2;
        
            if(n>0){         
                                
                // scraps already exist
                
                str = (prop.getProperty(""+n)).split(":");

                jTextArea1.setText(str[2]);
                jTextArea1.requestFocusInWindow();
                current=n;
                
            }
            else{               
                                
                // no scraps exist - so create 1st scrap and display
                
                current=1;
                count=1;
                                
                jTextArea1.setText(" ");
                jTextArea1.requestFocus();
                
                prop.setProperty(1+"","1"+":"+"1"+":"+"empty"); 
                prop.setProperty("count", count+"");
                prop.store(new FileOutputStream("scratch_pad.properties"), null);          
            
            }

            jLabel1.setText("Scrap "+ current);                

        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } 

}
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextArea1MouseClicked(evt);
            }
        });
        jTextArea1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextArea1FocusLost(evt);
            }
        });
        jScrollPane1.setViewportView(jTextArea1);

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
        );

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, "<");
        jButton1.setToolTipText("previous scrap");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton2, ">");
        jButton2.setToolTipText("next scrap");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton4, "save into file");
        jButton4.setToolTipText("save scrap in a text file");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jButton1)
                .add(18, 18, 18)
                .add(jButton2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 32, Short.MAX_VALUE)
                .add(jButton4)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton1)
                    .add(jButton2)
                    .add(jButton4))
                .add(22, 22, 22))
        );

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "jLabel1");

        org.openide.awt.Mnemonics.setLocalizedText(jButton3, "X");
        jButton3.setToolTipText("delete scrap");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)
                .add(86, 86, 86)
                .add(jButton3)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(jLabel1)
                .add(jLabel2)
                .add(jButton3))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(5, 5, 5)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 26, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextArea1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextArea1MouseClicked
    }//GEN-LAST:event_jTextArea1MouseClicked

    private void jTextArea1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextArea1FocusLost
     
        // Saves file when focus lost
        
            String[] str = new String[5],D=new String[5];
            int n;
            
            str = (prop.getProperty(current+"")).split(":");

            prop.setProperty(current+"",str[0]+":"+str[1]+":"+jTextArea1.getText());

//            BufferedReader b=new BufferedReader(new FileReader("scratch_pad.properties"));
//            D=  b.readLine().split(" ");
//            jLabel2.setText("Last edited : "+D[1]+" "+D[2]+" "+D[4]+" "+D[3]);
//            b.close();
            
       
    }//GEN-LAST:event_jTextArea1FocusLost

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

            

            String[] str = new String[5];
            int n;

            str = (prop.getProperty("" + current)).split(":");
            n=Integer.parseInt(str[0]);

            display(n);
            
  
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
                
        try {
            
           
            String[] str = new String[5];
            int n;
        
            str = (prop.getProperty("" + current)).split(":");

            if(count>current){               
                                
                n=Integer.parseInt(str[1]);
                
                current=n;
                display(n); 
                           

            }
            else{              

                count++;
                prop.setProperty(current+"", str[0]+":"+count+":"+str[2]);                 
                prop.setProperty(count+"",current+":"+count+": ");
                prop.setProperty("count", ""+count);

                            
                prop.store(new FileOutputStream("scratch_pad.properties"), null);                           
                display(count);
         
            }                        
       
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed

        // saves current scrap as a txt file
        
        String filename=null;                  
        JFileChooser chooser = new JFileChooser();
        
        
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.addChoosableFileFilter(new txt_file_filter());      
         
        int option = chooser.showSaveDialog(scratch_padTopComponent.this);
        if (option == JFileChooser.APPROVE_OPTION) {
          FileOutputStream fl = null;
            {
                Writer out = null;
                try {
                    filename = chooser.getSelectedFile().getPath();
                    System.out.println("filename" + filename);
                    fl = new FileOutputStream(filename + ".txt");
                    out = new OutputStreamWriter(fl, "UTF8");
                    out.write("/*************************************\n");
                    out.write("scrap created with \n\" SACK scratch pad for netbeans v1.0 \"");
                    out.write("\n*************************************/\n\n");
                    out.write("" + jTextArea1.getText());
                    out.close();
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                } finally {
                    try {
                        fl.close();
                    } catch (IOException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                    
                }
            }  
        }
  
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        try {
                   
            //deletes current scrap
            
            String[] str = new String[5],str1=new String[5],str2=new String[5];
            int n;
                    
            String prev,next;

            str = (prop.getProperty("" + current)).split(":");
            prev = str[0];
            next = str[1]; 
            
            if(current<=start){                   
                   
                // if current scrap is the 1st scrap
                
                start++;
                
                prop.setProperty("start",start+"");
                prop.remove("" + current);
                
                if(count==current){                                        
                    // if only one scrap was there
                    
                    display(0);
                    start=1;
                
                }
                else{
                str2= (prop.getProperty(next)).split(":");
                prop.setProperty(next, next+":"+str2[1]+":"+str2[2]); 
                prop.store(new FileOutputStream("scratch_pad.properties"), null);
                display(Integer.parseInt(next));
                }              
            }
            else{

                
                if(current<count){
                    // if current scrap is not 1st or last scrap    
                    
                    prop.remove("" + current); 
                    
                    str1 = (prop.getProperty(prev).split(":"));                
                    str2= (prop.getProperty(next)).split(":"); 
                    
                    prop.setProperty(prev, str1[0]+":"+next+":"+str1[2]);                 
                    prop.setProperty(next, prev+":"+str2[1]+":"+str2[2]);                  
                    prop.store(new FileOutputStream("scratch_pad.properties"), null);
                
                    display(Integer.parseInt(prev));
                }
                else{   
                    // if current scrap is last scrap
                    
                    count=Integer.parseInt(prev);  
                    prop.remove("" + current);                
                    str1 = (prop.getProperty(prev).split(":"));

               
                    prop.setProperty(prev, str1[0]+":"+prev+":"+str1[2]);                 
                    prop.setProperty("count",""+count);                 
                    prop.store(new FileOutputStream("scratch_pad.properties"), null);
                
                    display(Integer.parseInt(prev));
                }
            
            }

            
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
            
    }//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private static javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private static javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
       


               

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized scratch_padTopComponent getDefault() {
        if (instance == null) {
            instance = new scratch_padTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the scratch_padTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized scratch_padTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        win.grabFocus();
        if (win == null) {
            Logger.getLogger(scratch_padTopComponent.class.getName()).warning("Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof scratch_padTopComponent) {
            return (scratch_padTopComponent) win;
        }
        Logger.getLogger(scratch_padTopComponent.class.getName()).warning("There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    public @Override
    int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    public @Override
    void componentOpened() {

        try{
                    
            // load properties file
            prop.load(new FileInputStream("scratch_pad.properties"));
        } catch (IOException ex) {
            // if file does not exist then create
            
            FileOutputStream fos=null;
            try {

                fos = new FileOutputStream("scratch_pad.properties");
            } catch (FileNotFoundException ex2) {
                Exceptions.printStackTrace(ex2);
            } 
        }
        
                
        try {
            
            prop.load(new FileInputStream("scratch_pad.properties"));
            
            String count =prop.getProperty("count");  
            String start =prop.getProperty("start");
            
            if(count==null){
                prop.setProperty("count", ""+1);
                prop.setProperty("start", ""+1);
                prop.store(new FileOutputStream("scratch_pad.properties"), null);
                display(0);
               
            }
            else{
                this.count=Integer.parseInt(count);
                this.start=Integer.parseInt(start);
                display(this.count);           
            }


//            BufferedReader b=new BufferedReader(new FileReader("scratch_pad.properties"));
//            String[] D=  b.readLine().split(" ");
//            jLabel2.setText("Last edited : "+D[1]+" "+D[2]+" "+D[5]+" "+D[3]);
//            b.close();
                

 
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        

    }   
    

    public @Override
    void componentClosed() {
    // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    public @Override
    Object writeReplace() {
        return new ResolvableHelper();
    }

    protected @Override
    String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return scratch_padTopComponent.getDefault();
        }
    }
}
